<template>
  <div class="HomePage">
    <!-- 顶部开始 -->
    <el-row class="top">
      <!-- 顶部左边部分开始 -->
      <el-col :span="18" class="left">
        <!-- 工单销售统计 S -->
        <div class="statistics">
          <!-- 工单统计 S -->
          <div class="order">
            <!-- 标题开始 -->
            <div class="title">
              <div class="titleInfo">
                <div class="text">工单统计</div>
                <div class="time">{{ this.time.start.split(' ')[0].split('-').join('.')}} ~ {{ this.time.end.split(' ')[0].split('-').join('.')}}</div>
              </div>
            </div>
            <!-- 标题结束 -->
            <!-- 数据展示开始 -->
            <div class="infoNum">
              <div class="flex">
                <div>
                  <div class="num">{{ taskReportInfo.total }}</div>
                  <div class="text">工单总数（个）</div>
                </div>
              </div>
              <div class="flex">
                <div>
                  <div class="num">{{ taskReportInfo.completedTotal }}</div>
                  <div class="text">完成工单（个）</div>
                </div>
              </div>
              <div class="flex">
                <div>
                  <div class="num">{{ taskReportInfo.progressTotal }}</div>
                  <div class="text">进行工单（个）</div>
                </div>
              </div>
              <div class="flex">
                <div>
                  <div class="num">{{ taskReportInfo.cancelTotal }}</div>
                  <div class="text">取消工单（个）</div>
                </div>
              </div>
            </div>
            <!-- 数据展示结束 -->
          </div>
          <!-- 工单统计 N -->
          <!-- 销售统计 S -->
          <div class="sale">
            <!-- 标题开始 -->
            <div class="title">
              <div class="titleInfo">
                <div class="text">销售统计</div>
                <div class="time">{{ this.time.start.split(' ')[0].split('-').join('.')}} ~ {{ this.time.end.split(' ')[0].split('-').join('.')}}</div>
              </div>
            </div>
            <!-- 标题结束 -->
            <!-- 数据展示开始 -->
            <div class="infoNum">
              <div class="flex">
                <div>
                  <div class="num">{{ orderCount }}</div>
                  <div class="text">订单量（个）</div>
                </div>
              </div>
              <div class="flex">
                <div>
                  <div class="num">{{ Number(orderAmount / 1000000).toFixed(2) }}</div>
                  <div class="text">销售额（万元）</div>
                </div>
              </div>
            </div>
            <!-- 数据展示结束 -->
          </div>
          <!-- 销售统计 N -->
        </div>
        <!-- 工单销售统计 N -->
        <!-- 销售数据 S -->
        <div class="data">
          <!-- 标题开始 -->
          <div class="title">
            <div class="titleInfo">
              <div class="text">销售数据</div>
              <div class="time">{{ tiemCartData }}</div>
            </div>
            <div class="more">
              <div class="sub">
                <div class="item" :class="dataSwitch === '周' ? 'active' : '' " @click="getCartData('周')">周</div>
                <div class="item" :class="dataSwitch === '月' ? 'active' : '' " @click="getCartData('月')">月</div>
                <div class="item" :class="dataSwitch === '年' ? 'active' : '' " @click="getCartData('年')">年</div>
              </div>
            </div>
          </div>
          <!-- 标题结束 -->
          <div class="echarts">
            <!-- 销售趋势 S -->
            <div class="item sales" ref="sales"></div>
            <!-- 销售趋势 N -->
            <!-- 销售额分布 N -->
            <div class="item distribution" ref="distribution" v-show="showDistribution"></div>
            <el-empty :image="empty" description="暂无数据" v-show="!showDistribution"></el-empty>
            <!-- 销售趋势 N -->
          </div>
        </div>
        <!-- 销售数据 N -->
      </el-col>
      <!-- 顶部左边部分结束 -->
      <el-col :span="6">
        <div class="hotGoods">
          <!-- 标题开始 -->
          <div class="title">
            <div class="titleInfo">
              <div class="text">商品热榜</div>
              <div class="time">{{ this.time.start.split(' ')[0].split('-').join('.')}} ~ {{ this.time.end.split(' ')[0].split('-').join('.')}}</div>
            </div>
          </div>
          <!-- 标题结束 -->
          <!-- 列表开始 -->
          <div class="hotList">
            <HotGoodsList v-for="(item, index) in skuTop" :key="index" :index="index" :item="item"/>
          </div>
          <!-- 列表结束 -->
        </div>
      </el-col>
    </el-row>
    <!-- 顶部结束 -->
    <!-- 底部开始 -->
    <div class="bottom">
      <div class="info">
        <!-- 合作商点位数 S -->
        <div class="top5">
          <!-- 标题开始 -->
          <div class="title">
            <div class="titleInfo">
              <div class="text">合作商点位数Top5</div>
            </div>
            <div class="more">
              <i class="el-icon-more" @click="$router.push('/node/partner')"></i>
            </div>
          </div>
          <div class="topView">
            <div class="left top5Ec" ref="top5Ec"></div>
            <div class="right">
              <div class="view">
                <div class="num">{{ top5Point }}</div>
                <div class="str">点位数</div>
                <div class="num">{{ top5Partner }}</div>
                <div class="str">合作商数</div>
              </div>
            </div>
          </div>
          <!-- 标题结束 -->
        </div>
        <!-- 合作商点位数 N -->
        <!-- 异常设备监控 S -->
        <div class="error">
          <!-- 标题开始 -->
          <div class="title">
            <div class="titleInfo">
              <div class="text">异常设备监控</div>
            </div>
            <div class="more">
              <i class="el-icon-more" @click="$router.push('/vm/status')"></i>
            </div>
          </div>
          <!-- 标题结束 -->
          <!-- 故障列表开始 -->
          <div class="table" v-if="errorStatus.length">
            <el-table
            :data="errorStatus"
            style="width: 100%"
            height="100%">
              <el-table-column
                prop="time"
                label="故障时间"
              >
              </el-table-column>
              <el-table-column
                prop="innerCode"
                label="编号"
              >
              </el-table-column>
              <el-table-column
                prop="address"
                label="地址"
              >
              </el-table-column>
            </el-table>
          </div>
          <div class="table" v-else>
            <el-empty :image="empty" description="暂无数据"></el-empty>
          </div>
          <!-- 故障列表结束 -->
        </div>
        <!-- 异常设备监控 N -->
      </div>
    </div>
    <!-- 底部结束 -->
  </div>
</template>

<script>
// 引入工具
import { getQueryTime, getWeekToday } from '@/utils/tool'
// 引入API请求
import { getOrderAmount, getOrderCount, getTaskReportInfo, getSkuTop, getErrorStatus10, getTop5Partner, getTop5Point, getTop5, getAmountCollect, getRegionCollect } from '@/api/public'
// 引入商品热榜组件
import HotGoodsList from '@/components/HotGoodsList'
// 引入 echarts
import * as echarts from 'echarts'
export default {
  components: {
    HotGoodsList
  },
  data () {
    return {
      // 接收时间
      time: {},
      // 接收订单数
      orderCount: '',
      // 接收销售额
      orderAmount: '',
      // 工单部分
      taskReportInfo: {
        total: 0,
        completedTotal: 0,
        cancelTotal: 0,
        progressTotal: 0
      },
      // 商品热榜
      skuTop: [],
      // 异常设备监控
      errorStatus: [],
      empty: require('@/assets/empty.png'),
      // 周月年切换
      dataSwitch: '周',
      // 销售趋势
      salesEData: {
        title: {
          text: '销售趋势图',
          left: 'center',
          textStyle: {
            fontSize: 14
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line'
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['加载中...']
        },
        yAxis: {
          type: 'value',
          name: '单位：元'
        },
        series: [
          {
            name: '销售额',
            data: [0],
            type: 'line',
            smooth: true,
            symbolSize: 4,
            lineStyle: {
              width: 2.5
            },
            itemStyle: {
              color: '#FF5A5A'
            },
            areaStyle: {
              opacity: 0.4,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'red'
                },
                {
                  offset: 1,
                  color: '#ffffff80'
                }
              ])
            }
          }
        ]
      },
      // 销售额分布
      distributionEData: {
        title: {
          text: '销售额分布',
          left: 'center',
          textStyle: {
            fontSize: 14
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line'
          }
        },
        xAxis: {
          type: 'category',
          data: ['加载中...']
        },
        yAxis: {
          type: 'value',
          name: '单位：元'
        },
        series: [
          {
            name: '销售额',
            data: [0],
            type: 'bar',
            barWidth: 14,
            itemStyle: {
              color: '#91B0FF'
            }
          }
        ]
      },
      // Top5合作
      top5EData: {
        tooltip: {
          trigger: 'item'
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: true }
          }
        },
        series: [
          {
            type: 'pie',
            radius: [50, 100],
            center: ['50%', '50%'],
            roseType: 'radius',
            data: [
              { value: 1, name: '加载中' }
            ],
            itemStyle: {
              normal: {
                color: function (colors) {
                  const colorList = [
                    '#85A7FF',
                    '#99EBBD',
                    '#FFB18B',
                    '#C6EBFF',
                    '#BECCE6'
                  ]
                  return colorList[colors.dataIndex]
                }
              }
            }
          }
        ]
      },
      // 点位数
      top5Point: 0,
      // 合作商数
      top5Partner: 0,
      // 切换后的时间
      tiemCartData: '0000.00.00 ~ 0000.00.00',
      // 显示和隐藏 distribution
      showDistribution: true
    }
  },
  async created () {
    // 获取时间
    this.time = getQueryTime()
    // 获取销售额
    const { data: orderAmount } = await getOrderAmount(this.time)
    this.orderAmount = orderAmount
    // 获取订单数
    const { data: orderCount } = await getOrderCount(this.time)
    this.orderCount = orderCount
    // 获取工单数据
    const { data: taskReportInfo } = await getTaskReportInfo(this.time)
    // console.log(taskReportInfo)
    // 吧获取到的工单数组每项对应的值相加
    taskReportInfo.forEach(item => {
      this.taskReportInfo.total += item.total
      this.taskReportInfo.completedTotal += item.completedTotal
      this.taskReportInfo.cancelTotal += item.cancelTotal
      this.taskReportInfo.progressTotal += item.progressTotal
    })
    // 获取商品热榜
    const { data: skuTop } = await getSkuTop(this.time)
    this.skuTop = skuTop
    // 获取故障的设备列表
    const { data: errorStatus } = await getErrorStatus10()
    this.errorStatus = errorStatus
    // echarts
  },
  async mounted () {
    // 销售趋势
    this.salesEData && this.salesChart.setOption(this.salesEData)
    // 销售分布
    this.distributionEData && this.distributionChart.setOption(this.distributionEData)
    // 销售合作商前五
    this.top5EData && this.top5hart.setOption(this.top5EData)
    // 窗口大小发生变化重新渲染图表大小
    window.onresize = () => {
      this.salesChart.resize()
      this.distributionChart.resize()
      this.top5hart.resize()
    }
    // 获取合作商
    const { data: top5Partner } = await getTop5Partner()
    this.top5Partner = top5Partner
    // 获取点位数
    const { data: top5Point } = await getTop5Point()
    this.top5Point = top5Point
    // 获取Top5合作商
    const { data: top5 } = await getTop5()
    this.top5hart.setOption({
      series: [
        {
          data: top5
        }
      ]
    })
    // 更新销售数据
    this.getCartData('周')
  },
  methods: {
    // 更新数据
    async getCartData (data) {
      this.dataSwitch = data
      if (data === '周') {
        // 获取周数据
        const date = getWeekToday()
        console.log(date)
        // console.log(date)
        // 获取销售趋势数据
        const { data: amountCollect } = await getAmountCollect({
          collectType: 1,
          start: date.start,
          end: date.end
        })
        // console.log(amountCollect)
        // 更新销售趋势数据
        this.salesChart.setOption({
          xAxis: {
            data: date.data
          },
          series: [
            {
              name: '销售额',
              data: amountCollect.series
            }
          ]
        })
        // 获取销售分布数据区
        const { data: regionCollect } = await getRegionCollect({
          start: date.start,
          end: date.end
        })
        // console.log(regionCollect)
        // 更新销售分布数据
        this.distributionChart.setOption({
          xAxis: {
            data: regionCollect.xAxis
          },
          series: [
            {
              name: '销售额',
              data: regionCollect.series
            }
          ]
        })
        if (regionCollect.xAxis.length === 0) {
          this.showDistribution = false
        } else {
          this.showDistribution = true
        }
        this.tiemCartData = `${date.start.split('-').join('.')} ~ ${date.end.split('-').join('.')}`
      } else if (data === '月') {
        const date = getQueryTime()
        // console.log(date)
        // 获取销售趋势数据
        const { data: amountCollect } = await getAmountCollect({
          collectType: 1,
          start: date.start.split(' ')[0],
          end: date.end.split(' ')[0]
        })
        // console.log(amountCollect)
        // 格式化日期
        const xAxisData = amountCollect.xAxis.map(item => `${item.split('-')[1]}月${item.split('-')[2]}日`)
        // 更新销售趋势数据
        this.salesChart.setOption({
          xAxis: {
            data: xAxisData
          },
          series: [
            {
              name: '销售额',
              data: amountCollect.series
            }
          ]
        })
        // 获取销售分布数据区
        const { data: regionCollect } = await getRegionCollect({
          start: date.start.split(' ')[0],
          end: date.end.split(' ')[0]
        })
        // console.log(regionCollect)
        // 更新销售分布数据
        this.distributionChart.setOption({
          xAxis: {
            data: regionCollect.xAxis
          },
          series: [
            {
              name: '销售额',
              data: regionCollect.series
            }
          ]
        })
        if (regionCollect.xAxis.length === 0) {
          this.showDistribution = false
        } else {
          this.showDistribution = true
        }
        this.tiemCartData = `${date.start.split(' ')[0].split('-').join('.')} ~ ${date.end.split(' ')[0].split('-').join('.')}`
      } else {
        const date = getQueryTime()
        // console.log(date)
        // 获取销售趋势数据
        const { data: amountCollect } = await getAmountCollect({
          collectType: 2,
          start: date.start.split('-')[0] + '-01-01',
          end: date.end.split(' ')[0]
        })
        // console.log(amountCollect)
        // 格式化日期
        const xAxisData = amountCollect.xAxis.map(item => `${date.start.split('-')[0]}年${item.split('-')[1]}月`)
        // 更新销售趋势数据
        this.salesChart.setOption({
          xAxis: {
            data: xAxisData
          },
          series: [
            {
              name: '销售额',
              data: amountCollect.series
            }
          ]
        })
        // 获取销售分布数据区
        const { data: regionCollect } = await getRegionCollect({
          start: date.start.split('-')[0] + '-01-01',
          end: date.end.split(' ')[0]
        })
        // console.log(regionCollect)
        // 更新销售分布数据
        this.distributionChart.setOption({
          xAxis: {
            data: regionCollect.xAxis
          },
          series: [
            {
              name: '销售额',
              data: regionCollect.series
            }
          ]
        })
        if (regionCollect.xAxis.length === 0) {
          this.showDistribution = false
        } else {
          this.showDistribution = true
        }
        this.tiemCartData = `${date.start.split('-')[0]}.01.01 ~ ${date.end.split(' ')[0].split('-').join('.')}`
      }
    }
  },
  computed: {
    // *通过计算函数来创建echarts实例
    // 销售合作商前五
    top5hart () {
      const top5DOM = this.$refs.top5Ec
      return echarts.init(top5DOM)
    },
    // 销售分布
    distributionChart () {
      const distributionDOM = this.$refs.distribution
      return echarts.init(distributionDOM)
    },
    // 销售趋势
    salesChart () {
      const salesDOM = this.$refs.sales
      return echarts.init(salesDOM)
    }
  }
}
</script>

<style lang="scss" scoped>
.HomePage {
  .top {
    // 顶部右侧内容
    .left {
      // 右边工单与销售统计
      .statistics {
        display: flex;
        // 工单统计
        .order {
          flex: 13;
          margin-right: 20px;
          // 设置背景图片
          background-image: url("~@/assets/HomeTask.png"),
            url("@/assets/HomeTaskTwo.png");
          // 关闭背景图重复
          background-repeat: no-repeat;
          // 背景图定位
          background-position: right bottom, 0 0;
          // 背景颜色
          background-color: #e9f3ff;
          // infoNum里的
          .infoNum .num {
            color: #072074;
            text-shadow: 2px 4px 7px rgb(85 132 255 / 50%)
          }
          // infoNum里的
          .infoNum .text {
            color: #91a7dc;
          }
        }
        // 销售统计
        .sale {
          flex: 11;
          // 设置背景属性
          background: #fbefe8 url("~@/assets/HomeSale.png") no-repeat right bottom;
          // infoNum里的
          .infoNum .num {
            color: #ff5757;
            text-shadow: 2px 4px 7px rgb(255 99 85 / 50%);
          }
          // infoNum里的
          .infoNum .text {
            color: #de9690;
          }
        }
        // 工单与销售的公共样式
        .order,
        .sale {
          height: 126px;
          border-radius: 20px;
          padding: 20px;
        }
        // 数据展示
        .infoNum {
          display: flex;
          height: 100%;
          // 让文字居中
          .flex {
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: center;
          }
          .num {
            font-size: 36px;
            font-weight: 700;
          }
          .text {
            margin-top: 3px;
            font-size: 12px;
          }
        }
      }
      // 数据表部分
      .data {
        margin-top: 20px;
        height: 352px;
        border-radius: 20px;
        padding: 20px;
        box-sizing: border-box; // 开启内减
        background: #fff;
        .echarts {
          display: flex;
          height: 100%;
          .item {
            flex: 50%;
          }
        }
        .el-empty {
          width: 50%;
        }
        .title .more .sub {
          width: 129px;
          height: 34px;
          display: flex;
          align-items: center;
          justify-content: space-around;
          font-size: 14px;
          border-radius: 10px;
          background: #f8fafd;
          color: #9ca3b4;
          .item {
            width: 37px;
            height: 25px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            &.active {
              box-shadow: 0 0 4px 0 rgb(0 0 0 / 11%);
              border-radius: 7px;
              background: #fff;
              color: #000;
              font-weight: 700;
            }
          }
        }
      }
    }
    // 商品热榜
    .hotGoods {
      height: 538px;
      margin-left: 20px;
      border-radius: 20px;
      padding: 20px;
      background: #fff;
      box-sizing: border-box; // 开启内减
      .hotList {
        margin-top: 20px;
        ::v-deep .listItem:nth-child(1) .num {
          background-image: url('~@/assets/HomeHotGoodsListOne.png');
          color: #8e5900;
        }
        ::v-deep .listItem:nth-child(2) .num {
          background-image: url('~@/assets/HomeHotGoodsListTree.png');
          color: #494949;
        }
        ::v-deep .listItem:nth-child(3) .num {
          background-image: url('~@/assets/HomeHotGoodsListTwo.png');
          color: #cf6d3d;
        }
      }
    }
  }
  // 下面两个模块
  .bottom {
    margin-top: 20px;
    .info {
      display: flex;
      // 合作商
      .top5 {
        flex: 16;
        margin-right: 20px;
        .topView {
          height: 100%;
          display: flex;
          .left {
            flex: 1;
          }
          .right {
            width: 264px;
            display: flex;
            align-items: center;
            .view {
              width: 116px;
              height: 183px;
              padding-top: 57px;
              padding-left: 38px;
              background: linear-gradient(135deg,transparent,#f8f8f9 0) 0 0,linear-gradient(-135deg,transparent 12px,#f8f8f9 0) 100% 0,linear-gradient(-45deg,transparent,#f8f8f9 0) 100% 100%,linear-gradient(45deg,transparent 12px,#f8f8f9 0) 0 100%;
              background-size: 50% 50%;
              background-repeat: no-repeat;
              .str {
                font-size: 12px;
                margin-top: 6px;
              }
              .num {
                margin-top: 20px;
                line-height: 33px;
                font-size: 24px;
                font-weight: 700;
                color: #072074;
              }
              .num:nth-child(1){
                margin-top: 0
              }
            }
          }
        }
      }
      // 异常监控
      .error {
        flex: 11;
        .table {
          height: calc(100% - 20px);
          width: 100%;
        }
      }
      // 合作商和异常监控公共
      .top5,
      .error {
        height: 353px;
        border-radius: 20px;
        padding: 20px;
        box-sizing: border-box; // 开启内减
        background: #fff;
      }
    }
  }
  // 公共标题
  .title {
    display: flex;
    justify-content: space-between;
    // 标题部分
    .titleInfo {
      display: flex;
      align-items: center;
      .text {
        font-size: 16px;
        font-weight: 700;
        color: #333;
      }
      .time {
        font-size: 12px;
        margin-left: 10px;
        color: #999;
      }
    }
    // 更多部分
    .more {
      i {
        zoom: 0.67; // 自己造的 icon 需要缩放
        color: #5f84ff !important;
        border: 2px solid #5f84ff;
        border-radius: 20px;
        padding: 2px;
        cursor: pointer;
      }
    }
  }
  // 暂无数据部分
  .el-empty {
    height: 100%;
    width: 100%;
  }
}
</style>
